package com.bjsxt;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**TCP通信，一对多应用，一对多问答型服务器
 * 服务端*/

/*定义消息处理线程，这里定义一个线程就可以，接收与发送消息放在一起*/
class Msg2 extends Thread{
    Socket socket;
    public Msg2(Socket socket){
        this.socket=socket;
    }
    @Override
    public void run() {
        this.msg();
    }
    private void msg(){
        BufferedReader br = null;//用于读数据进来
        PrintWriter pw = null;//用于写消息出去
        try {
            //将消息读进来的流对象
            br = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
            //将消息写回去的流对象
            pw = new PrintWriter(this.socket.getOutputStream());
            while (true){
                //把读进来的消息返回去
                pw.println(br.readLine());
                pw.flush();
            }
        }catch (Exception e){
            System.out.println(this.socket.getInetAddress()+"断线了");
            e.printStackTrace();
        }finally {
            if(br != null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(pw != null){
                pw.close();
            }
            if(this.socket != null){
                this.socket=null;
            }
        }
    }
}
public class EchoServer02 {
    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        try{
            serverSocket = new ServerSocket(2222);
            //用无限循环实现服务端对多个客户端,不停监听端口
            while (true){
                Socket socket = serverSocket.accept();
                new Msg2(socket).start();
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(serverSocket != null){
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
